//
//  TextViewController.m
//  WebView加载文件
//
//  Created by xiacl on 2018/9/5.
//  Copyright © 2018年 a2345. All rights reserved.
//

#import "TextViewController.h"

@interface TextViewController ()

@end

@implementation TextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"txt";

    self.webView.scalesPageToFit = YES;
//    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self test];
}


- (void)test {
    ///编码可以解决 .txt 中文显示乱码问题
    
    NSStringEncoding *useEncodeing = nil;
    
    //带编码头的如utf-8等，这里会识别出来 self.path是文件地址（Users/a1/Library/Developer/CoreSimulator/Devices/62525235-2FB8-40D6-8B16-1F94704B7EEA/data/Containers/Data/Application/635003EB-D704-4EC4-8333-6CF80B5E3FCB/Documents/22237.text）
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"test.text" ofType:nil];
    NSString *body = [NSString stringWithContentsOfFile:path usedEncoding:useEncodeing error:nil];
//   body = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    //识别不到，按GBK编码再解码一次.这里不能先按GB18030解码，否则会出现整个文档无换行bug。
    
    if (!body) {
        body = [NSString stringWithContentsOfFile:path encoding:0x80000632 error:nil];
    }
    
    //还是识别不到，按GB18030编码再解码一次.
    if (!body) {
        body = [NSString stringWithContentsOfFile:path encoding:0x80000631 error:nil];
    }
    
    NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
    [self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"utf-8" baseURL:nil];
    return;
    //展现
    if (body) {
        [self.webView loadHTMLString:body baseURL: nil];
        
    } else {
        NSURL *url = [NSURL fileURLWithPath:path];
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
        [self.webView loadRequest:request];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
